package com.acwing.lc.part1;

import java.util.ArrayList;
import java.util.List;

/**
 * @author rkc
 * @date 2022/9/12 16:15
 */
public class LC39组合总和 {

    private int[] nums;
    private List<List<Integer>> ans = new ArrayList<>();
    private List<Integer> path = new ArrayList<>();

    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        nums = candidates;
        dfs(0, target, 0);
        return ans;
    }

    private void dfs(int start, int target, int sum) {
        if (sum == target) {
            ans.add(new ArrayList<>(path));
            return;
        }
        if (sum > target) return;
        for (int i = start; i < nums.length; i++) {
            if (sum + nums[i] > target) continue;
            path.add(nums[i]);
            dfs(i, target, sum + nums[i]);
            path.remove(path.size() - 1);
        }
    }
}
